<template>
    <el-pagination
        v-model:currentPage="form.page"
        v-model:page-size="form.page_size"
        small
        background
        :page-sizes="options.pageSizes"
        :layout="options.layout"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
    </el-pagination>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, inject } from 'vue';
import type { PropType } from 'vue';
import { ElPagination } from 'element-plus';

const currentGroupId: number | string = inject('currentGroupId', 0);

const options = ref<any>({
    pageSizes: [15, 30, 50, 100],
    layout: 'total, prev, pager, next, sizes'
});
const form = ref<any>({});

interface PropsType {
    modelValue: PropType<any>;
    total: number;
}

const props = withDefaults(defineProps<PropsType>(), {
    modelValue: () => ({}),
    total: 0
});

const emits = defineEmits<{
    (e: 'update:modelValue', form: any): void;
    (e: 'change', form: any): void;
}>();

watch(
    () => currentGroupId,
    () => reset()
);

/**
 * @description: 分页器size变化事件处理
 * @param {*} val
 * @return {*}
 */
const handleSizeChange = async val => {
    form.value.page = 1;
    form.value.page_size = val;
    emits('update:modelValue', form.value);
    emits('change', form.value);
};

/**
 * @description: 分页器当前页变化事件处理
 * @param {*} val
 * @return {*}
 */
const handleCurrentChange = async val => {
    form.value.page = val;
    emits('update:modelValue', form.value);
    emits('change', form.value);
};

/**
 * @description: 初始化分页器
 * @return {*}
 */
const initFormData = () => {
    form.value['page'] = 1;
    form.value['page_size'] = 15;
};

/**
 * @description: 重置分页器
 * @return {*}
 */
const reset = () => {
    initFormData();
    emits('update:modelValue', form.value);
};

onMounted(() => {
    initFormData();
});

defineExpose({
    reset
});
</script>
<style lang="scss" scoped>
.el-pagination {
    margin-top: 10px;
}
</style>
